package com.ipzoe.web.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateException;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ipzoe.act.domain.Activity;
import com.ipzoe.act.domain.ActivitySignup;
import com.ipzoe.act.service.IActivityService;
import com.ipzoe.act.service.IActivitySignupService;
import com.ipzoe.cms.domain.Article;
import com.ipzoe.cms.service.IArticleService;
import com.ipzoe.common.core.domain.AjaxResult;
import com.ipzoe.common.core.domain.entity.SysDictData;
import com.ipzoe.common.exception.CustomException;
import com.ipzoe.mem.domain.Member;
import com.ipzoe.system.domain.HotCity;
import com.ipzoe.system.service.IHotCityService;
import com.ipzoe.system.service.IRegionService;
import com.ipzoe.system.service.ISysDictDataService;
import com.ipzoe.system.service.ISysDictTypeService;
import com.ipzoe.web.convert.ActivityConvert;
import com.ipzoe.web.convert.RegionConvert;
import com.ipzoe.web.core.page.WebPageInfo;
import com.ipzoe.web.model.ActivityVO;
import com.ipzoe.web.model.HotCityVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/activity")
public class ActivityController extends WebBaseController{

    @Autowired
    private IActivityService iActivityService;
    @Autowired
    private ISysDictDataService iSysDictDataService;
    @Autowired
    private ISysDictTypeService iSysDictTypeService;
    @Autowired
    private IHotCityService iHotCityService;
    @Autowired
    private IRegionService iRegionService;
    @Autowired
    private IActivitySignupService iActivitySignupService;
    @Autowired
    private IArticleService iArticleService;

    /**
     * 搜索条件：<br>
     * <p>
     *     tp=1 今天  tp=2 明天 tp=3 本周 tp=4本月 tp=2020-08-02|2020-08-28 自定义<br>
     *     cp=1 城市<br>
     *     sp=1 状态<br>
     *     pp=1 活动权限
     *     pg=1 分页
     * </p>
     *
     * @param model
     * @return
     */
    @GetMapping({"/list"})
    public String index(@RequestParam(required = false)Long cp,
                        @RequestParam(required = false)String sp,
                        @RequestParam(required = false)String pp,
                        @RequestParam(defaultValue = "1",required = false) int pg,
                        @RequestParam(required = false)String tp, Model model, HttpServletRequest request){

        //获取活动权限
        List<SysDictData> activityPermissionDictDataList = iSysDictTypeService.selectDictDataByType("act_active_permission");
        model.addAttribute("permissionDictDataList", activityPermissionDictDataList);

        //获取活动状态数据字典
        List<SysDictData> activityStatusDictDataList = iSysDictTypeService.selectDictDataByType("act_active_status");
        model.addAttribute("statusDictDataList", activityStatusDictDataList);

        //获取热门城市
        model.addAttribute("hotCityList", iHotCityService.listHotCityWithRegionInfo());

        LambdaQueryWrapper<Activity> activityLqw = new LambdaQueryWrapper<>();
        int pageSize = 20;
        activityLqw.eq(StrUtil.isNotBlank(pp) ,Activity::getPermission, pp);
        activityLqw.eq(StrUtil.isNotBlank(sp), Activity::getStatus, sp);
        activityLqw.eq(cp != null, Activity::getCityCode, cp);
        activityLqw.apply("1".equals(tp), "date_format(begin_time,'%y%m%d') <= date_format({0},'%y%m%d') and date_format(end_time,'%y%m%d') >= date_format({0},'%y%m%d') ", DateUtil.today());
        activityLqw.apply("2".equals(tp), "date_format(begin_time,'%y%m%d') <= date_format({0},'%y%m%d') and date_format(end_time,'%y%m%d') >= date_format({0},'%y%m%d') ", DateUtil.tomorrow().toString());
        activityLqw.apply("3".equals(tp), "date_format(begin_time,'%y%m%d') <= date_format({0},'%y%m%d') and date_format(end_time,'%y%m%d') >= date_format({1},'%y%m%d') ", DateUtil.endOfWeek(new Date()).toString(), DateUtil.beginOfWeek(new Date()).toString());
        activityLqw.apply("4".equals(tp), "date_format(begin_time,'%y%m%d') <= date_format({0},'%y%m%d') and date_format(end_time,'%y%m%d') >= date_format({1},'%y%m%d') ", DateUtil.endOfMonth(new Date()).toString(), DateUtil.beginOfMonth(new Date()).toString());
        if(StrUtil.isNotEmpty(tp) && tp.contains("|")){
            String[] tpArr = StrUtil.split(tp,"|");
            String beginStr = tpArr[0];
            String endStr = tpArr[1];
            boolean enableDate = true;
            try{
               DateUtil.parseDate(beginStr);
               DateUtil.parseDate(endStr);
           }catch (DateException e){
                enableDate = false;
           }
            if(enableDate){
                activityLqw.apply("date_format(begin_time,'%y%m%d') <= date_format({0},'%y%m%d') and date_format(end_time,'%y%m%d') >= date_format({1},'%y%m%d') ", endStr, beginStr);
                model.addAttribute("tpBegin", beginStr);
                model.addAttribute("tpEnd", endStr);
            }
        }
        activityLqw.orderByDesc(Activity::getId);
        Page<Activity> page = iActivityService.page(new Page<>(pg, pageSize), activityLqw);
        Page<ActivityVO> voPage = ActivityConvert.INSTANCE.convert(page);
        voPage.getRecords().forEach(r->{
            r.setCity(iRegionService.getById(r.getCityCode()));
            r.setPermissionDictLabel(iSysDictDataService.selectDictLabel("act_active_permission", String.valueOf(r.getPermission())));
            r.setStatusDictLabel(iSysDictDataService.selectDictLabel("act_active_status", String.valueOf(r.getStatus())));
        });
        model.addAttribute("activityPage", new WebPageInfo<ActivityVO>(voPage, 8));

        return getLocaleHtml("activity-list.html", request);
    }

    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") Long id, Model model, HttpServletRequest request){

        Activity activity = iActivityService.getById(id);
        if(activity==null){
            return "/error/404.html";
        }

        activity.setPvNum(activity.getPvNum()+1);
        iActivityService.updateById(activity);

        ActivityVO activityVO = ActivityConvert.INSTANCE.convert(activity);
        activityVO.setCity(iRegionService.getById(activityVO.getCityCode()));
        activityVO.setPermissionDictLabel(iSysDictDataService.selectDictLabel("act_active_permission", String.valueOf(activityVO.getPermission())));
        activityVO.setStatusDictLabel(iSysDictDataService.selectDictLabel("act_active_status", String.valueOf(activityVO.getStatus())));

        model.addAttribute("activity", activityVO);

        //协议文章
        Article article = iArticleService.getById(1L);
        model.addAttribute("article", article);

        return getLocaleHtml("activity-detail.html", request);
    }

    @ResponseBody
    @PostMapping("/signUp")
    public AjaxResult signUp(Long activityId, String name, String nickname, String phone, String email, int agree, HttpServletRequest request){

        if(agree != 1){
            throw new CustomException(400,"请阅读并同意《DAN潜水平台用户协议》");
        }

        Member member = (Member) request.getAttribute("member");
        iActivityService.signUp(activityId, name, nickname, phone, email, member);

        return AjaxResult.success();
    }


}
